<template>
  <div>
    <div v-if="showwechat">
      <Row :gutter="16" class="ivu-mt-8 ivu-mb-8">
        <Col
          span="8"
          v-for="item in datacontent"
          :key="item.id"
          style="cursor: pointer;"
        >
          <div @click="dataparams(item.id)">
            <Card dis-hover :class="dataid === item.id ? 'ivu-active' : ''">
              <Avatar
                class="ivu-fl ivu-mr-16"
                size="large"
                :src="item.avatar"
              />
              <Row type="flex" align="middle" justify="space-between">
                <Col span="20">
                  <h3 class="sky-nickname">
                    <Ellipsis
                      :text="item.nickname"
                      :length="18"
                      :tooltip="true"
                    />
                  </h3>
                  <p class="sky-wxid">{{ item.friend_wechatno }}</p>
                </Col>
                <Col span="4" v-if="+item.is_bind === 1">
                  <a
                    @click.stop="unbind(item)"
                    v-hasC="{
                      name: '-v1-patient-index-unbind-wechat',
                      flag: '/v1/patient/index/unbind-wechat',
                    }"
                  >
                    解绑
                  </a>
                </Col>
              </Row>
            </Card>
          </div>
        </Col>
      </Row>
      <Divider style="margin: 12px;" />
      <Row :gutter="32">
        <Col span="8">
          <DescriptionList class="ivu-mt-16" :col="1">
            <Description>
              <Select
                v-if="wxlist.length > 1"
                v-model="paramsrecord.wechat_id"
                v-width="180"
                @on-change="changewx"
              >
                <Option
                  v-for="item in wxlist"
                  :value="item.wechatid"
                  :key="item.wechatid"
                  >{{ item.wechatnick }}</Option
                >
              </Select>
              <p v-else-if="(wxlist.length = 1)">
                {{ wxlist[0] ? wxlist[0].wechatnick : "" }}
              </p>
            </Description>
            <Description>
              <tag
                v-for="(item, index) in dataparamslist.tags_arr"
                :key="index"
                >{{ item }}</tag
              >
            </Description>
            <!-- <Description term="微信号：">{{
                            dataparamslist.friend_wechatno ||
                            dataparamslist.friendid
                        }}</Description>
                        <Description term="地区："
                            >{{ dataparamslist.province }}
                            {{ dataparamslist.city }}</Description
                        > -->
            <Description term="来源：">{{
              dataparamslist.source_type_str
            }}</Description>
            <Description term="备注名：">{{
              dataparamslist.remark_name
            }}</Description>
            <Description term="微信状态：">
              <Badge
                status="success"
                v-if="+dataparamslist.state === 0"
                :text="dataparamslist.state_str"
              />
              <Badge
                status="warning"
                v-else-if="+dataparamslist.state === 1"
                :text="dataparamslist.state_str"
              />
              <Badge
                status="error"
                v-else-if="+dataparamslist.state === 2"
                :text="dataparamslist.state_str"
              />
              <Badge
                status="warning"
                v-else-if="+dataparamslist.state === 3"
                :text="dataparamslist.state_str"
              />
              <Badge
                status="error"
                v-else-if="+dataparamslist.state === 4"
                :text="dataparamslist.state_str"
              />
            </Description>
            <Description term="加好友天数：">{{
              dataparamslist.create_day
            }}</Description>
            <Description term="未互动天数：">{{
              dataparamslist.unchat_day
            }}</Description>
            <Description term="通过时间：">{{
              dataparamslist.create_time
            }}</Description>
          </DescriptionList>
          <Button
            type="primary"
            @click="changedata"
            v-hasC="{
              name: 'v1-site-repair-wechat-message-queue',
              flag: 'v1/site/repair-wechat-message-queue',
            }"
            >同步数据</Button
          >

          <Button
            type="primary"
            class="ivu-ml-8"
            @click="lyModal = true"
            v-hasC="{
              name: '-business-patient-voice-queue',
              flag: 'v1/business/patient/voice-queue',
            }"
            >同步录音</Button
          >
        </Col>
        <Col span="16">
          <div class="sky-record">
            <chatDetail
              :paramsrecord="paramsrecord"
              :userInfo="userInfo"
              ref="liaotian"
            />
          </div>
        </Col>
      </Row>
    </div>
    <div class="wechatnull" v-else>
      <p>暂无信息</p>
      <p>提示：此处不显示患者绑定关系，可能是咨询微信号通讯录未同步</p>
    </div>
    <Modal v-model="modal" title="选择时间">
      <DatePicker
        type="daterange"
        v-model="date"
        ref="date"
        :options="dateOption"
        @click.native="nativeClick"
        placement="bottom-end"
        placeholder="选择开始时间和结束时间"
        style="width: 300px"
      />
      <div slot="footer">
        <Button @click="handleCancel">取消</Button>
        <Button type="primary" @click="handleSubmit">确定</Button>
      </div>
    </Modal>
    <Modal v-model="lyModal" title="选择时间">
      <DatePicker
        type="daterange"
        v-model="lydate"
        ref="lydate"
        :options="dateOption"
        placement="bottom-end"
        placeholder="选择开始时间和结束时间"
        style="width: 300px"
      />
      <div slot="footer">
        <Button @click="lyCancel">取消</Button>
        <Button type="primary" @click="lySubmit">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { patientindexwechatinfo, patientindexunbindwechat } from "@/api/hqapi";
import { wechatmessageQueue, voiceQueue } from "@/api/hqapi/indexone.js";
import chatDetail from "@/pages/clue/chatrecord";
import dayjs from "dayjs";
import util from "@/libs/util";
export default {
  name: "wechat",
  components: { chatDetail },
  props: ["userInfo"],
  data() {
    return {
      modal: false,
      lyModal: false,
      wxlist: [],
      dataid: "",
      paramsrecord: { wechat_id: "", friend_id: "", id: "" },
      params: { patient_user_id: "" },
      datacontent: [],
      showwechat: true,
      dataparamslist: {},
      // date: [],
      date: [
        // dayjs().startOf('month').format('YYYY-MM-DD'),
        dayjs("2023-2-18").format("YYYY-MM-DD"),
        dayjs("2023-2-17")
          .add(60, "days")
          .format("YYYY-MM-DD"),
        // dayjs().startOf('month').format('DD') === '01' ? dayjs().startOf('month').format('YYYY-MM-DD') : dayjs().subtract(1, 'day').format('YYYY-MM-DD')
      ],
      lydate: [
        dayjs()
          .add(-7, "days")
          .format("YYYY-MM-DD"),
        dayjs().format("YYYY-MM-DD"),
      ],
      dateOption: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        },
      },
    };
  },
  mounted() {},
  methods: {
    // 限制60天选择范围
    nativeClick(e) {
      const target = this.$refs["date"].$refs["pickerPanel"];
      target.handlePickClick = () => {
        // 这里加这么一段
        const { from, selecting } = target["rangeState"];
        if (from && selecting) {
          this.dateOption = {
            disabledDate(value) {
              const startTime = new Date(from);
              const endTime = new Date(from);
              startTime.setDate(from.getDate() - 60);
              endTime.setDate(from.getDate() + 60);
              return !(value >= startTime && value <= endTime);
            },
          };
        }
      };
      const { from, selecting } = target["rangeState"];
      if (from && selecting) {
        this.dateOption = {
          disabledDate(value) {
            const startTime = new Date(from);
            const endTime = new Date(from);
            startTime.setDate(from.getDate() - 60);
            endTime.setDate(from.getDate() + 60);
            return !(value >= startTime && value <= endTime);
          },
        };
      } else {
        this.dateOption = {
          disabledDate(date) {
            return date && date.valueOf() > Date.now();
          },
        };
      }
    },
    askData(id) {
      this.dataid = "";
      this.paramsrecord = { wechat_id: "", friend_id: "", id: "" };
      this.datacontent = [];
      this.dataparamslist = {};
      this.params.patient_user_id = id;
      this.askDatas();
    },
    askDatas() {
      patientindexwechatinfo(this.params).then((res) => {
        if (res.list.length > 0) {
          this.datacontent = res.list;
          this.dataparams(res.list[0].id);
          this.showwechat = true;
        } else {
          this.showwechat = false;
        }
      });
    },
    dataparams(id) {
      this.dataid = id;
      this.datacontent.forEach((item) => {
        // console.log(item,'item1')
        if (item.id === id) {
          this.dataparamslist = item.wechat_list[0];
          this.wxlist = item.wechat_list;
          this.paramsrecord.wechat_id = item.wechat_list[0].wechatid;
          this.paramsrecord.friend_id = item.friendid;
          // this.paramsrecord.id=item.id
          this.wechatmessagelists(item);
        }
      });
    },
    wechatmessagelists(row) {
      this.$nextTick(() => {
        this.$refs.liaotian.askDatas("end");
      });
    },
    changewx(item) {
      // console.log(item,'changex')
      this.paramsrecord.wechat_id = item;
      this.dataparamslist = this.wxlist.filter((ee) => {
        return ee.wechatid === item;
      })[0];
      if (this.paramsrecord.wechat_id && this.paramsrecord.friend_id) {
        this.$nextTick(() => {
          this.$refs.liaotian.askDatas("end");
        });
      }
    },
    unbind(item) {
      let params = {
        wechat_id: item.friend_wechatno,
        id: this.params.patient_user_id,
      };
      this.$Modal.confirm({
        title: "解绑提示",
        content: "<p>解绑后微信聊天记录将不在患者微信信息中展示</p>",
        onOk: () => {
          patientindexunbindwechat(params).then(() => {
            this.$Message.success("解绑成功");
            this.askData(this.params.patient_user_id);
          });
        },
      });
    },
    changedata() {
      this.modal = true;
    },
    handleCancel() {
      this.modal = false;
      this.date = [
        // dayjs().startOf('month').format('YYYY-MM-DD'),
        dayjs("2023-2-18").format("YYYY-MM-DD"),
        dayjs("2023-2-17")
          .add(60, "days")
          .format("YYYY-MM-DD"),
        // dayjs().startOf('month').format('DD') === '01' ? dayjs().startOf('month').format('YYYY-MM-DD') : dayjs().subtract(1, 'day').format('YYYY-MM-DD')
      ];
    },
    lyCancel() {
      this.lyModal = false;
      this.lydate = [
        dayjs()
          .add(-7, "days")
          .format("YYYY-MM-DD"),
        dayjs().format("YYYY-MM-DD"),
      ];
    },
    lySubmit() {
      if (this.lydate.length > 0) {
        const params = {
          type: "swoole",
          imei: this.dataparamslist.deviceid,
          wechatid: this.paramsrecord.wechat_id,
          start_time: this.lydate[0]
            ? dayjs(this.lydate[0]).format("YYYY-MM-DD")
            : "",
          end_time: this.lydate[1]
            ? `${dayjs(this.lydate[1]).format("YYYY-MM-DD")}${23}:${59}`
            : "",
        };
        voiceQueue(params).then((res) => {
          // console.log(res,'res');
          this.$Message.success("正在同步，5分钟内请勿重复操作");
          this.lyCancel();
        });
      } else {
        this.$Message.error("请选择日期后再操作");
      }
    },
    handleSubmit() {
      if (this.date.length > 0) {
        const params = {
          type: 3,
          project_id: localStorage.getItem("currentProject"),
          wechatid: this.paramsrecord.wechat_id,
          friendid: this.paramsrecord.friend_id,
          start_time: this.date[0]
            ? dayjs(this.date[0]).format("YYYY-MM-DD")
            : "",
          end_time: this.date[1]
            ? `${dayjs(this.date[1]).format("YYYY-MM-DD")} ${23}:${59}`
            : "",
        };
        wechatmessageQueue(params).then((res) => {
          // console.log(res,'res');
          this.$Message.success("正在同步，5分钟内请勿重复操作");
          this.handleCancel();
        });
      } else {
        this.$Message.error("请选择日期后再操作");
      }
    },
  },
};
</script>
<style scoped>
.ivu-weixin {
  color: #777;
  font-size: 12px;
}

.sky-wxid {
  color: #777;
  margin-top: 2px;
  font-size: 12px;
}

.sky-record {
  /* border: 1px solid #dcdcdc; */
  height: 440px;
}

.ivu-active {
  border: 1px solid #2d8cf0;
}

.person {
  color: #999;
}
</style>
<style scoped>
.hqcard {
  position: absolute;
  top: 110px;
  left: 24px;
  right: 24px;
  bottom: 24px;
  overflow: auto;
  margin: auto;
}

.wechatnull {
  height: calc(100vh - 390px);
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.wechatnull p:last-child {
  color: red;
  line-height: 35px;
}
</style>
